package com.dgut.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dgut.dto.ListFormDto;
import com.dgut.dto.Result;
import com.dgut.dto.StatisticAO;
import com.dgut.pojo.Account;
import com.dgut.pojo.UserInfo;
import com.dgut.service.AccountService;
import com.dgut.service.DailyFormService;
import com.dgut.service.UserInfoService;
import com.dgut.service.impl.AccountServiceImpl;
import com.dgut.service.impl.DailyFormServiceImpl;
import com.dgut.service.impl.UserInfoServiceImpl;
import com.dgut.utils.ExcelUtil;
import com.dgut.utils.MyDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AccountServiceImpl accountService;
    @Autowired
    DailyFormServiceImpl dailyFormService;
    @Autowired
    UserInfoServiceImpl userInfoService;

    //查找所有账号信息
    @GetMapping("/getAccountWithUserInfo")
    public Result getAccountWithUserInfo(@RequestParam(defaultValue ="1") int current, @RequestParam(defaultValue="10") int size,@RequestParam(required = false,defaultValue = "-1") int isLocked,@RequestParam(required=false) String order){
        Result result = new Result();
        Page<Account> accountPage = new Page<>(current,size);
        accountService.getAccountWithUserInfo(accountPage,isLocked,order);
        result.setData(accountPage);
        result.setMsg("获取账号信息成功");
        result.setCode(200);
        return result;
    }

    //更新某个账号的锁定情况
    @GetMapping("/updateIsLocked")
    public Result updateIsLocked(@RequestParam("accountId") int accountId,@RequestParam("isLocked")  int isLocked){
        Result result = new Result();
        try {
            accountService.updateIsLocked(accountId,isLocked);
            result.setCode(200);
            result.setMsg("状态更新成功");
        } catch (Exception e) {
            result.setCode(0);
            result.setMsg("状态更新失败");
        }
        return result;
    }

    //查找填报情况（一般只查询某一天的）
    @PostMapping("/getFormList")
    public Result getFormList(@RequestBody ListFormDto listFormDto){
        Result result = new Result();
        Page<Map<String,Object>> page = new Page<>(listFormDto.getCurrent(),listFormDto.getSize());
        Page<Map<String, Object>> formList = dailyFormService.getFormList(page,listFormDto);
        result.setMsg("成功获取数据");
        result.setCode(200);
        result.setData(formList);
        return result;
    }

    //查询没有填报的人员名单(默认为当天，查询信息中不包括姓名)
    @PostMapping("/getNoFillList")
    public Result getNoFillList(@RequestBody ListFormDto listFormDto){
        Result result = new Result();
        Page<UserInfo> page = new Page<>(listFormDto.getCurrent(),listFormDto.getSize());
        Page<UserInfo> noFillList = userInfoService.getNoFillList(page, listFormDto);
        result.setCode(200);
        result.setMsg("获取数据成功");
        result.setData(noFillList);
        return result;
    }

    //查询用户的基本信息
    @PostMapping("/getUserInfoList")
    public Result getUserInfoList(@RequestBody ListFormDto listFormDto){
        Result result = new Result();
        Page<UserInfo> userInfoPage = new Page<>(listFormDto.getCurrent(), listFormDto.getSize());
        Page<UserInfo> userInfoList = userInfoService.getUserInfoList(userInfoPage, listFormDto);
        result.setCode(200);
        result.setMsg("获取数据成功");
        result.setData(userInfoList);
        return result;
    }

    //获取大数据报表
    @GetMapping("/getStatisticForm")
    public Result getStatisticForm(){
        Result result = new Result();
        Map<String, List<StatisticAO>> statisticForm = dailyFormService.getStatisticForm();
        result.setCode(200);
        result.setMsg("获取数据成功");
        result.setData(statisticForm);
        return result;
    }

    //填报情况导出为excel
    @PostMapping("/getFormListExcel")
    public void getFormListExcel(@RequestBody ListFormDto listFormDto, HttpServletResponse response){
        //数据处理
        //将size设置为-1，将不会进行分页
        Page<Map<String,Object>> page = new Page<>(1,-1);
        Page<Map<String, Object>> formList = dailyFormService.getFormList(page, listFormDto);
        //获取全部数据
        String date = MyDateUtil.getNthSimpleDate(listFormDto.getCreateTime(),0);
        String datePattern=MyDateUtil.getDateFromPattern(listFormDto.getCreateTime(),"MM月dd日");
        String dateBefore = MyDateUtil.getDateFromPattern(listFormDto.getCreateTime(),-14,"yyyy年MM月dd日");
        String dateKey = dateBefore+"至"+datePattern;
        List<Map<String,Object>> records = formList.getRecords();
        //题干
        List<String> titles = Arrays.asList("账号名", "姓名", "性别", "身份类别", "学院", "班级", "填报时间", "身体状况", dateKey + "是否到达或途径疫情防控重点地区",
                dateKey + "是否接触过'近14天出入过疫情重点防控地区'的人员", dateKey + "是否有接触过疑似/确诊病例", "是否在莞隔离医学观察",
                "目前是否在莞", dateKey + "是否有离莞出行的行动", "是否为重点人群", "同住的家庭成员是否有如下情况", "备注", "今日体温");
        //内容
        List<List<String>> values = new ArrayList<>();
        if(!records.isEmpty()){
            for (Map<String, Object> record : records) {
                ArrayList<String> strings = new ArrayList<>();
                strings.add((String) record.get("账号名"));
                strings.add((String) record.get("姓名"));
                strings.add((String) record.get("性别"));
                strings.add((String) record.get("身份类别"));
                strings.add((String) record.get("学院"));
                strings.add((String) record.get("班级"));
                strings.add(MyDateUtil.getSimpleDate((Date) record.get("填报时间")));
                strings.add((String) record.get("身体状况"));
                strings.add((String) record.get(dateKey + "是否到达或途径疫情防控重点地区"));
                strings.add((String) record.get(dateKey + "是否接触过'近14天出入过疫情重点防控地区'的人员"));
                strings.add((String) record.get(dateKey + "是否有接触过疑似/确诊病例"));
                strings.add((String) record.get("是否在莞隔离医学观察"));
                strings.add((String) record.get("目前是否在莞"));
                strings.add((String) record.get(dateKey + "是否有离莞出行的行动"));
                strings.add((String) record.get("是否为重点人群"));
                strings.add((String) record.get("同住的家庭成员是否有如下情况"));
                strings.add((String) record.get("备注"));
                strings.add((String) record.get("今日体温"));
                values.add(strings);  //添加到内容中
            }
        }
        //工作表名
        String sheetName = datePattern+"的填报情况";
        HSSFWorkbook hssfWorkbook = ExcelUtil.getHSSFWorkbook(sheetName, titles, values);
        //让列宽自适应
        ExcelUtil.setSizeColumn(hssfWorkbook.getSheet(datePattern+"的填报情况"),titles.size());

        //文件名
        String fileName = null;
        try {
            fileName = URLEncoder.encode(sheetName + ".xlsx", "UTF-8");
//            fileName = URLEncoder.encode(sheetName + ".xlsx", "utf-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        try {
            // 形成输出流
            OutputStream osOut = response.getOutputStream();
            // 将指定的字节写入此输出流
            hssfWorkbook.write(osOut);
            // 刷新此输出流并强制将所有缓冲的输出字节被写出
            osOut.flush();
            // 关闭流
            osOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //将没有进行填报的人员名单导出为excel (默认为当天，查询信息中不包括姓名)
    @PostMapping("/getNoFillListExcel")
    public void getNoFillListExcel(@RequestBody ListFormDto listFormDto,HttpServletResponse response) {
        Page<UserInfo> page = new Page<>(1,-1);
        Page<UserInfo> noFillList = userInfoService.getNoFillList(page, listFormDto);
        List<UserInfo> records = noFillList.getRecords();
        List<String> titles = Arrays.asList("学号","姓名", "性别", "身份类型","所在校区","学院", "班级");
        List<List<String>> values = new ArrayList<>();
        if(!records.isEmpty()){
            for (UserInfo record : records) {
                ArrayList<String> strings = new ArrayList<>();
                strings.add(record.getUsername());
                strings.add(record.getName());
                strings.add(record.getGender());
                strings.add(record.getIdentityCategory());
                strings.add(record.getSchoolLocation());
                strings.add(record.getDepartment());
                strings.add(record.getClassname());
                values.add(strings);  //添加到内容中
            }
        }
        String datePattern=MyDateUtil.getDateFromPattern(listFormDto.getCreateTime(),"yyyy年MM月dd日");

        //工作表名
        String sheetName = datePattern+"没有填报的人员名单";
        HSSFWorkbook hssfWorkbook = ExcelUtil.getHSSFWorkbook(sheetName, titles, values);
        //让列宽自适应
        ExcelUtil.setSizeColumn(hssfWorkbook.getSheet(sheetName),titles.size());

        //文件名
        String fileName = null;
        try {
            fileName = URLEncoder.encode(sheetName + ".xlsx", "utf-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        try {
            // 形成输出流
            OutputStream osOut = response.getOutputStream();
            // 将指定的字节写入此输出流
            hssfWorkbook.write(osOut);
            // 刷新此输出流并强制将所有缓冲的输出字节被写出
            osOut.flush();
            // 关闭流
            osOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //用户的基本信息导出为excel
    @PostMapping("/getUserInfoListExcel")
    public void getUserInfoListExcel(@RequestBody ListFormDto listFormDto,HttpServletResponse response){
        Page<UserInfo> userInfoPage = new Page<>(1,-1);
        Page<UserInfo> userInfoList = userInfoService.getUserInfoList(userInfoPage, listFormDto);
        List<UserInfo> records = userInfoList.getRecords();
        List<String> titles = Arrays.asList("学号","姓名", "性别", "学院", "班级", "证件类型", "证件号码", "身份类别", "所在校区", "籍贯", "户籍", "家庭住址", "电话号码", "紧急联系人", "联系人号码");
        List<List<String>> values = new ArrayList<>();
        if(!records.isEmpty()){
            for (UserInfo record : records) {
                ArrayList<String> strings = new ArrayList<>();
                strings.add(record.getUsername());
                strings.add(record.getName());
                strings.add(record.getGender());
                strings.add(record.getDepartment());
                strings.add(record.getClassname());
                strings.add(record.getCertificateType());
                strings.add(record.getIdNumber());
                strings.add(record.getIdentityCategory());
                strings.add(record.getSchoolLocation());
                strings.add(record.getNativePlace());
                strings.add(record.getHouseholdRegister());
                strings.add(record.getAddress());
                strings.add(record.getPhoneNumber());
                strings.add(record.getContacts());
                strings.add(record.getContactNumber());
                values.add(strings); //添加到内容中
            }
        }
        //工作表名
        String sheetName = "用户的基本信息表";
        HSSFWorkbook hssfWorkbook = ExcelUtil.getHSSFWorkbook(sheetName, titles, values);
        //让列宽自适应
        ExcelUtil.setSizeColumn(hssfWorkbook.getSheet(sheetName),titles.size());
        //文件名
        String fileName = null;
        try {
            fileName = URLEncoder.encode(sheetName + ".xlsx", "utf-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        try {
            // 形成输出流
            OutputStream osOut = response.getOutputStream();
            // 将指定的字节写入此输出流
            hssfWorkbook.write(osOut);
            // 刷新此输出流并强制将所有缓冲的输出字节被写出
            osOut.flush();
            // 关闭流
            osOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //大数据报表导出为excel
    @GetMapping("/getStatisticFormExcel")
    public void getStatisticFormExcel(HttpServletResponse response) {
        String datePattern=MyDateUtil.getDateFromPattern(new Date(),"yyyy年MM月dd日");
        //获取近七天的日期
        String day = MyDateUtil.getNthSimpleDate(0);
        String day1 = MyDateUtil.getNthSimpleDate(-1);
        String day2 = MyDateUtil.getNthSimpleDate(-2);
        String day3 = MyDateUtil.getNthSimpleDate(-3);
        String day4 = MyDateUtil.getNthSimpleDate(-4);
        String day5 = MyDateUtil.getNthSimpleDate(-5);
        String day6 = MyDateUtil.getNthSimpleDate(-6);
        //留出第一列给每行的行名
        List<String> titles = Arrays.asList(" ",day, day1, day2, day3, day4, day5,day6);
        List<String> days = Arrays.asList(day, day1, day2, day3, day4, day5,day6);
        List<List<String>> values = new ArrayList<>();
        Map<String, List<StatisticAO>> statisticForm = dailyFormService.getStatisticForm();
        if(!statisticForm.isEmpty()){
            for (String key : statisticForm.keySet()) {
                ArrayList<String> strings = new ArrayList<>();
                strings.add(key);   //map中的每一个key都是每一行的第一列
                List<StatisticAO> statisticAOS = statisticForm.get(key);
                //查询每个日期对应的数量
                for (String s : days) {
                    for (StatisticAO statisticAO : statisticAOS) {
                        if(s.equals(statisticAO.getDate())){
                            strings.add(String.valueOf(statisticAO.getCount()));
                            break;
                        }
                    }
                }
                values.add(strings);  //添加到内容中
            }
        }
        //工作表名
        String sheetName = datePattern+"近七天的大数据报表";
        HSSFWorkbook hssfWorkbook = ExcelUtil.getHSSFWorkbook(sheetName, titles, values);
        //让列宽自适应
        ExcelUtil.setSizeColumn(hssfWorkbook.getSheet(sheetName),titles.size());
        //文件名
        String fileName = null;
        try {
            fileName = URLEncoder.encode(sheetName + ".xlsx", "utf-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        try {
            // 形成输出流
            OutputStream osOut = response.getOutputStream();
            // 将指定的字节写入此输出流
            hssfWorkbook.write(osOut);
            // 刷新此输出流并强制将所有缓冲的输出字节被写出
            osOut.flush();
            // 关闭流
            osOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
